package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;
import com.fz.us.oa.core.entity.com.Seal;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.SealService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/25.
 */
@Controller
@RequestMapping(value = "/com/seal")
public class SealController extends BaseController {
    private static final long serialVersionUID = -7313412608485999157L;

    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private SealService sealService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private FileManagerService fileManagerService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> dictItems = getDictItems(user,"sealName");
        if (StringUtils.isNotEmpty(keyId)){
            Seal seal=sealService.get(keyId);
            String fileId="";
            if(seal.getFile()!=null&&seal.getFile().size()>0){
                for(FileManage file:seal.getFile()){
                    fileId+=file.getId()+",";
                }
            }
            model.addAttribute("fileId", fileId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("seal", seal);
        }
        model.addAttribute("dictItems", dictItems);
        model.addAttribute("user", user);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/seal_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            Seal seal=sealService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            String fileId="";
            if(seal.getFile()!=null&&seal.getFile().size()>0){
                for(FileManage file:seal.getFile()){
                    fileId+=file.getId()+",";
                }
            }
            model.addAttribute("fileId", fileId);
            model.addAttribute("stepNo", stepNo);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("seal", seal);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/seal_read";
    }

    /**
     * 保存Model数据
     */
    private Seal saveModel(User user, String keyId, String useType, String datPlanReturn, String sealDictItemId,
                           String useReason, String numSeal, String fileIds) {

        Seal seal = null;
        if (StringUtils.isBlank(keyId)) {
            seal = new Seal();
            seal.setCreater(user);
            seal.setCompany(user.getCompany());

            seal.setName("印章名称");
        } else {
            seal = sealService.get(keyId);
        }

        int usetype = Integer.valueOf(useType);
        seal.setUseType(usetype);

        if (usetype==2 && StringUtils.isNotBlank(datPlanReturn)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                seal.setDatPlanReturn(sdf.parse(datPlanReturn));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (StringUtils.isNotBlank(sealDictItemId)) {
            DictItem sealDictItem = dictItemService.get(sealDictItemId);
            seal.setSealDictItem(sealDictItem);
            seal.setName(sealDictItem.getName());
        }

        if (StringUtils.isNotBlank(useReason)) {
            seal.setUseReason(useReason);
        }

        if (StringUtils.isNotBlank(numSeal)) {
            seal.setNumSeal(Integer.valueOf(numSeal));
        }

        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
        }
        seal.setFile(fileManageList);

        if (seal.getForm() == null) {
            seal.setForm("印章使用申请表");
        }

        return seal;
    }
    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String useType,
                       String datPlanReturn,
                       String sealDictItemId,
                       String useReason,
                       String numSeal,
                       String fileIds) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Seal seal = saveModel(user, keyId, useType, datPlanReturn, sealDictItemId, useReason, numSeal, fileIds);
        if(StringUtils.isNotEmpty(keyId)){
            sealService.update(seal);
            rMap.put("message", "更新成功");
        } else {
            sealService.save(seal, "com.fz.us.oa.core.entity.com.Seal");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     *提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String useType,
                         String datPlanReturn,
                         String sealDictItemId,
                         String useReason,
                         String numSeal,
                         String fileIds, String curDutyId, String comment) throws ParseException{

        Map<String,Object> rMap=new HashMap<String,Object>();
        Seal seal = saveModel(user,keyId,useType,datPlanReturn,sealDictItemId,useReason,numSeal,fileIds);
        seal.setDateApply(new Date());
        if(seal.getUseType()==2){
            seal.setNumStatus(1);
            seal.setTxtStatus("未还");
        } else {
            seal.setNumStatus(2);
            seal.setTxtStatus("已还");
        }

        if (StringUtils.isNotEmpty(keyId)) {
            sealService.approve(seal, dutyService.get(curDutyId), comment);
        } else {
            sealService.commit(seal, "com.fz.us.oa.core.entity.com.Seal", dutyService.get(curDutyId));
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Seal seal=sealService.get(keyId);
        sealService.approve(seal, dutyService.get(curDutyId), comment);

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Seal seal=sealService.get(keyId);
            sealService.back(seal, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Seal seal=sealService.get(keyId);
            sealService.deny(seal, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);

        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //申请中
                searchResult = sealService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Seal", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},params);
            }else if(viewtype.equals("2")){
                //外借印章
                params.put("numStatus", 1);
                searchResult = sealService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Seal", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("3")){
                //已归还
                params.put("numStatus", 2);
                searchResult = sealService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.Seal", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }
        }else{
            //所有单子
            searchResult = sealService.paging(null,null,order,
                    "com.fz.us.oa.core.entity.com.Seal",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }

        List<Seal> sealList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Seal seal: sealList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(seal.getId())?"":seal.getId());
            rMap.put("name", StringUtils.isEmpty(seal.getName())?"":seal.getName());

            if (seal.getSealDictItem() != null) {
                DictItem sealDictItem = seal.getSealDictItem();
                rMap.put("sealDictItemId", sealDictItem.getId());
                String definedName = dictItemService.getDefinedName(seal.getCompany().getId(), sealDictItem.getId());
                rMap.put("sealDictItemName", StringUtils.isEmpty(definedName)?sealDictItem.getName():definedName);
            }

            if(seal.getUseType()==1){
                rMap.put("useType", "内部使用");
            }else{
                rMap.put("useType", "外借使用");
            }
            rMap.put("txtStatus", seal.getTxtStatus());
            rMap.put("creater", seal.getCreater()==null?"": seal.getCreater().getName());
            rMap.put("processStateName", seal.getProcessState()==null?"": seal.getProcessState().value());
            rMap.put("createTime", seal.getCreateTime()==null?"": DataUtil.DateTimeToString(seal.getCreateTime()));
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 弹出归还确认对话框
     */
    @RequestMapping(value = "return/{keyId}", method = RequestMethod.GET)
    public String openDialog(@CurrentUser User user, Model model,
                             @PathVariable String keyId) {
        model.addAttribute("keyId", keyId);
        return "/com/seal_return_dialog";
    }

    /**
     * 保存实际归还日期
     */
    @RequestMapping(value = "savereturn/{keyId}", method = RequestMethod.POST)
    public Object saveDialogReturn(@CurrentUser User user,@PathVariable String keyId, String datFactReturn) {
        Seal seal = sealService.get(keyId);

        if (StringUtils.isNotBlank(datFactReturn)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                seal.setDatFactReturn(sdf.parse(datFactReturn));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        seal.setNumStatus(2);
        seal.setTxtStatus("已还");

        return ajaxJson(sealService.saveEntity(seal));
    }


}
